package com.tywj.navigation.map

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.TextWatcher
import android.text.style.ForegroundColorSpan
import android.view.WindowManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.amap.api.location.AMapLocation
import com.amap.api.maps.AMap.OnCameraChangeListener
import com.amap.api.maps.model.CameraPosition
import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.core.PoiItem
import com.amap.api.services.geocoder.GeocodeResult
import com.amap.api.services.geocoder.GeocodeSearch
import com.amap.api.services.geocoder.GeocodeSearch.OnGeocodeSearchListener
import com.amap.api.services.geocoder.RegeocodeQuery
import com.amap.api.services.geocoder.RegeocodeResult
import com.amap.api.services.poisearch.PoiResult
import com.amap.api.services.poisearch.PoiSearch
import com.amap.api.services.poisearch.PoiSearch.OnPoiSearchListener
import com.tywj.lib.core.common.extension.gone
import com.tywj.lib.core.common.extension.onClick
import com.tywj.lib.core.common.extension.visible
import com.tywj.lib.core.common.util.BarUtil
import com.tywj.lib.core.common.util.ResourcesUtil
import com.tywj.lib.location.entity.LocationEntity
import com.tywj.lib.route.RouteParam
import com.tywj.lib.route.RouteUtil
import com.tywj.navigation.R
import com.tywj.navigation.base.BaseMapActivity
import com.tywj.navigation.city.ChooseCityActivity
import com.tywj.navigation.entity.CityEntity
import com.tywj.navigation.route.NavigationRoute
import com.tywj.navigation.tool.MapTool
import com.tywj.navigation.tool.MyLocation
import com.tywj.panda.customer.common.provider.INavigationService
import kotlinx.android.synthetic.main.navigation_activity_selected_address.*


/**
 * @desc 选择地址(出发地、目的地)
 * @author June Yang
 * @date 2020/5/13
 * https://lbs.amap.com/api/android-sdk/guide/create-map/show-map
 */

@Route(path = NavigationRoute.NAVIGATION_SELECTED_ADDRESS)
class NavigationSelectedAddress : BaseMapActivity() {

    companion object {
        // 高度地图poiItem
        const val DATA_POI_ITEM = "poi_item"

        // 搜索内容
        const val PARAM_CONTENT = "content"

        //是否是出发地
        const val PARAM_FROM_PATH = "from"

        const val REQUEST_CITY = 8000
    }

    // 当前用户位置
    private var curLocation: AMapLocation? = null

    // 自定义地图定位
    private lateinit var myLocation: MyLocation

    //地图选择点
    private var local: PoiItem? = null

    // 是否是第一次获取定位
    private var isFirstLocation = false

    private var currentCity = MapTool.CITY_DEFAULT

    //搜索地址列表
    private lateinit var mAdapter: NavigationAddressAdapter

    private var list = ArrayList<PoiItem>()

    override fun getLayoutID(): Int = R.layout.navigation_activity_selected_address

    // 搜索内容
    private var content = ""

    private var fromPath = 0

    private var titleAddressTips = ResourcesUtil.getString(R.string.navigation_start_point_tips)

    override fun initVariable(savedInstanceState: Bundle?) {
        super.initVariable(savedInstanceState)

        // 保持屏幕常亮
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)

        myLocation = MyLocation()

        tvCityName.text = currentCity


        val param = RouteParam(this)

        content = param.getString(PARAM_CONTENT)

        fromPath = param.getInt(PARAM_FROM_PATH)

        if (fromPath == INavigationService.FROM_END) {
            titleAddressTips = ResourcesUtil.getString(R.string.navigation_end_point_tips)
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)

        BarUtil.setStatusBarColor(this, ResourcesUtil.getColor(R.color.common_white))

        etChooseAddress.setText(content)
        etChooseAddress.setSelection(content.length)
        initRecycleView()
    }


    override fun initListener() {
        super.initListener()

        myLocation.setOnLocationChangedListener {
            curLocation = it
        }

        tvCityName.onClick {
            RouteUtil.getServiceProvider(INavigationService::class.java)?.toSelectCity()?.navigation(this, REQUEST_CITY)
        }

        mAdapter.setOnItemClickListener { _, _, position ->
            //  返回搜索结果
            returnSearchResult(mAdapter.data[position])
        }

        ivDelete.onClick {
            etChooseAddress.setText("")
            gone(llRvList)
        }

        ivHind.onClick {
            gone(llRvList)
        }

        tvChooseAddressPoint.onClick {
            if (local != null) {
                returnSearchResult(local)
            } else {
                shortToast(R.string.navigation_please_choose_address)
            }
        }

        etChooseAddress.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(p0: Editable?) {
                searchLocation()
            }

            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }
        })

        map.setOnCameraChangeListener(object : OnCameraChangeListener {
            override fun onCameraChange(cameraPosition: CameraPosition) {}
            override fun onCameraChangeFinish(cameraPosition: CameraPosition) {
                val latLonPoint =
                    LatLonPoint(cameraPosition.target.latitude, cameraPosition.target.longitude)
                val query = RegeocodeQuery(latLonPoint, 200f, GeocodeSearch.AMAP)
                val geocoderSearch = GeocodeSearch(this@NavigationSelectedAddress)
                geocoderSearch.setOnGeocodeSearchListener(object : OnGeocodeSearchListener {
                    override fun onRegeocodeSearched(regeocodeResult: RegeocodeResult, i: Int) {
                        local = regeocodeResult.regeocodeAddress.pois[0]

                        updateSelectedTipsAddress(local)
                    }

                    override fun onGeocodeSearched(geocodeResult: GeocodeResult, i: Int) {}
                })
                geocoderSearch.getFromLocationAsyn(query)
            }
        })


    }

    override fun loadDataOnCreate() {
        super.loadDataOnCreate()
        searchLocation()
    }

    private fun searchLocation() {
        val mContent = etChooseAddress.text.toString().trim()
        if (mContent.isNotEmpty()) {
            visible(ivDelete)
            searchPOI(mContent, currentCity)
        } else {
            gone(ivDelete)
        }
    }

    private fun returnSearchResult(poiItem: PoiItem?) {
        val intent = Intent()
        intent.putExtra(DATA_POI_ITEM, poiItem)
        setResult(Activity.RESULT_OK, intent)
        finish()
    }


    private fun initRecycleView() {
        mAdapter = NavigationAddressAdapter()
        rvList.layoutManager = LinearLayoutManager(this)
        rvList.adapter = mAdapter
    }

    //TODO:是否考虑分页
    private fun searchPOI(key: String, city: String) {
        val query = PoiSearch.Query(key, "", city)
        query.pageSize = 20 // 设置每页最多返回多少条poiitem
        query.pageNum = 0 //设置查询页码
        val poiSearch = PoiSearch(applicationContext, query)
        poiSearch.setOnPoiSearchListener(object : OnPoiSearchListener {
            override fun onPoiSearched(poiResult: PoiResult, i: Int) {
                if (poiResult.pois.isNotEmpty()) {
                    list.clear()
                    list = poiResult.pois

                    if (list.isNotEmpty()) {
                        mAdapter.setNewData(list)
                        visible(llRvList)
                    } else {
                        gone(llRvList)
                    }
                }
            }

            override fun onPoiItemSearched(poiItem: PoiItem, i: Int) {}
        })
        poiSearch.searchPOIAsyn()
    }

    override fun onMyLocationChange(location: LocationEntity) {
        super.onMyLocationChange(location)

        if (!isFirstLocation) {
            // 第一次获取定位数据，将地址显示到该位置
            isFirstLocation = true
            toLocation(location.latitude, location.longitude, MapTool.ZOOM_LEVEL_DEFAULT)
        }
    }

    private fun updateSelectedTipsAddress(poiItem: PoiItem?) {
        val textChoose = ResourcesUtil.getString(R.string.navigation_choose)
        val textTips = titleAddressTips

        if (poiItem != null) {

            val textStr = SpannableStringBuilder()
                .append(textChoose)
                .append(poiItem.title)
                .append(textTips)

            textStr.setSpan(
                ForegroundColorSpan(ResourcesUtil.getColor(R.color.common_green_0F)),
                textChoose.length,
                textChoose.length + poiItem.title.length,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            tvChooseAddressPoint.text = textStr

        } else {
            tvChooseAddressPoint.text =
                ResourcesUtil.getString(R.string.navigation_please_choose_address)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {

                REQUEST_CITY -> {
                    val city: CityEntity = data!!.getParcelableExtra(ChooseCityActivity.PARAMS_CITY)

                    MapTool.CITY_CODE = city.cityCode

                    if (city.cityName.isNotEmpty()) {
                        currentCity = city.cityName
                        MapTool.CITY_DEFAULT = currentCity
                        tvCityName.text = currentCity
                    }
                }
            }
        }
    }
}